package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Sound;
import com.itheima.service.mongo.SoundService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;


import java.util.List;
@DubboService
public class SoundServiceImpl implements SoundService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存语音
     * @param sound
     */
    public void saveSound(Sound sound) {
        //保存到mongo中
        mongoTemplate.save(sound);
    }

    /**
     * 点击接收语音按钮，随机查询一个语音消息返回，在听完语音后，可以选择喜欢或者不喜欢，如果双方互相喜欢那么可以配对成功互相关注。
     * - 每日的接受数量限制
     * - 对于语音，只能被一个人获取  获取之后进行删除
     * @param userId
     * @return
     */
    public List<Sound> receiveSound(Long userId,String gender) {
        //1.随机获取一条数据
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("userId").nin(userId).and("gender").nin(gender)),  // 排除掉自己发的语音和性别相同的语音
                Aggregation.sample(1));
        AggregationResults<Sound> results = mongoTemplate.aggregate(aggregation, "sound", Sound.class);  //只有一条数据

        List<Sound> sounds = results.getMappedResults();

        //进行判断
        if (sounds == null || sounds.size() == 0 || sounds.isEmpty()){
            return null;
        }
        // 删除这一条数据
        mongoTemplate.remove(sounds.get(0));
        return sounds;

    }
}
